// 星星评分展示
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class starRating extends StatefulWidget {
  // 初始化一些参数
  final double rating; // 当前分数
  final double maxRating; // 满分
  final int count; // 评分个数
  final double size; // 评分大小
  final Color unselectedColor; // 没有选中颜色
  final Color selectedColor; // 选中颜色
  final Widget unselectedImage; // 未选中Image
  final Widget selectedImages; // 选中Image

  starRating({
    required this.rating,
    this.maxRating = 10,
    this.count = 5,
    this.size = 30,
    this.unselectedColor = const Color(0xffbbbbbb),
    this.selectedColor = const Color(0xffff0000),
    Widget? unselectedImage,
    Widget? selectedImage,
  })  : unselectedImage = (unselectedImage ??
                Icon(Icons.star_border, color: unselectedColor, size: size))
            as Widget,
        selectedImages = (selectedImage ??
            Icon(Icons.star, color: selectedColor, size: size)) as Widget;

  @override
  State<StatefulWidget> createState() {
    return _starRatingState();
  }
}

class _starRatingState extends State<starRating> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Row(mainAxisSize: MainAxisSize.min, children: buildUnselectedStar()),
        Row(mainAxisSize: MainAxisSize.min, children: buildSelectedStar())
      ],
    );
  }

  // 没有选中的星星
  List<Widget> buildUnselectedStar() {
    return List.generate(widget.count, (index) {
      return widget.unselectedImage;
    });
  }

  // 选中的星星
  List<Widget> buildSelectedStar() {
    // 1、 创建 starts
    List<Widget> stars = [];
    var selectedColor;
    final star = widget.selectedImages;

    // 2、 构建 满星 start
    double oneValue = widget.maxRating / widget.count;
    int entireCount = (widget.rating / oneValue).floor();
    for (int i = 0; i < entireCount; i++) {
      stars.add(star);
    }

    // 3、构建部分填充star
    double leftWidth = ((widget.rating / oneValue) - entireCount) * widget.size;
    final halfStar = ClipRect(
      clipper: StartClipper(leftWidth),
      child: star,
    );
    stars.add(halfStar);

    // 如果填写的星星超过个数时
    if (stars.length > widget.count) {
      return stars.sublist(0, widget.count);
    }

    return stars;
  }
}

// 自定义裁剪
class StartClipper extends CustomClipper<Rect> {
  double width;
  StartClipper(this.width);
  @override
  getClip(Size size) {
    return Rect.fromLTRB(0, 0, width, size.height);
  }

  @override
  bool shouldReclip(StartClipper oldClipper) {
    return oldClipper.width != this.width;
  }
}
